#include <array>
#include <string>
#include <vector>

class Solution {
public:
    std::array<int,20001> ss;
    int subarraysWithKDistinct(std::vector<int>& nums, int k) {
        return cal(nums,k)-cal(nums,k-1);
    }
    int cal(std::vector<int> &nums,int k){
        int n = nums.size();
        int ans = 0 ;
        ss.fill(0);
        int co = 0;
        for(int r=0,l=0;r<n;r++)
        {
            if (++ss[nums[r]]==1)
            {
                co++;
            }
           while (co>k)
           {
               if (--ss[nums[l++]]==0)
               {
                   co--;
               }
           }
            if (co<=k)
            {
                ans+=r-l+1;
            }
        }
        return ans;
    }
};